<?php
namespace Home\Controller;

use Think\Controller;
use Home\Event\WeixinEvent;
use Think\Exception;

class IndexController extends Controller {
    protected $wx_obj;
    protected $token;
    public function __construct(){
        $this->wx_obj = A('Weixin','Event');
        $this->token = C('TOKEN');
    }
    public function index(){
        //die('111');
        if(isset($_GET["echostr"])){
            $stat = $this->checkSignature();
            if($stat){
                echo $_GET["echostr"];
                exit;
            }
        }else{
            $this->reponseMsg();
        }
    }
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = $this->token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function simplexml(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)) {
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            return $postObj;
        }
        return false;
    }

    public function reponseMsg(){
        //1.获取到微信推送过来post数据（xml格式）
        $postarr = $this -> simplexml();
        //2.处理消息类型，并设置回复类型和内容
        switch (strtolower($postarr->MsgType)) {
            case 'event':
                //用户时间触发操作
                $this->receiveEvent($postarr);
                break;
            case 'text':
                //回复文本或者是其他
                $this->textAct($postarr);
                break;

            default:
                //回复文本或者是友好提示

        }

    }

    public function textAct($postarr) {
        switch ($postarr->Content) {
            case '1':
                $content = '你输入的是1';
                break;
            case '2':
                $content = '你输入的是2';
                break;
            case '3':
                $content = '你输入的是3';
                break;
            case '4':
                $content = '你输入的是4';
                break;
            default:
                $content = '你说的啥？';
        }
        return responseText($postarr, $content, true);
    }

    public function eventAct($postarr) {

        if (strtolower($postarr->Event) == 'subscribe') {

            responseText($postarr, 'hi,感谢关注怡臣优选，开启精致生活！现在开始选择离您最近的商城购物吧。快捷/安全/品质/便利是我们的服务宗旨！', true);
            $stat = $this->addUser($postarr);
            //用户订阅11

        } elseif (strtoupper($postarr->Event) == 'SCAN') {
            //用户扫码
            $stat = $this->addUser($postarr);
            responseText($postarr, 'hi,感谢关注怡臣优选，开启精致生活！现在开始选择离您最近的商城购物吧。快捷/安全/品质/便利是我们的服务宗旨！', true);
        }  /*elseif (strtoupper($postarr->Event) == 'LOCATION') {
            //用户上报地理位置
            responseText($postarr, '不约不约,就算你给了我地址', true);
        }*/
    }

    public function receiveEvent($object)
    {
        $contentStr = "";
        switch (strtoupper($object->Event))
        {
            case "SUBSCRIBE":
                //用户订阅
                //如果是扫描分销会员二维码进来
                $parameter = strtolower($object->EventKey);
                $keyArray = explode("_", $parameter);
                if (!preg_match('/[a-zA-Z]/',$keyArray[1]) && !empty($keyArray[1]) ){
                  $res_add = $this->is_fx_scan($keyArray[1],$object);

                  M('test')->add(['msg'=>'扫描分销会员二维码进来']);

                  if($res_add['status'] === false){
                       responseText($object, $res_add['msg'], true);
                  }
                }else{
                    //扫描 店铺二维码进来
                    $stat = $this->addUser($object);
                }
                responseText($object, 'hi,感谢关注怡臣优选，开启精致生活！现在开始选择离您最近的商城购物吧。快捷/安全/品质/便利是我们的服务宗旨！', true);

                break;
            case "SCAN":
                //再次扫描情况

                //如果是扫描分销会员二维码进来
                $keyA = strtolower($object->EventKey);

                if (!preg_match('/[a-zA-Z]/',$keyA)){
                    $res_add = $this->is_fx_scan($keyA,$object);

                    M('test')->add(['msg'=>'扫描分销会员二维码进来']);

                    if($res_add['status'] === false){
                        responseText($object, $res_add['msg'], true);
                    }
                }else{
                    //扫描 店铺二维码进来
                    $stat = $this->addUser($object);
                }

                //用户订阅=>已经关注
                responseText($object, 'hi,感谢关注怡臣优选，开启精致生活！现在开始选择离您最近的商城购物吧。快捷/安全/品质/便利是我们的服务宗旨！', true);
                break;
            case "UNSUBSCRIBE":
                break;
            case "LOCATION":
                $fromUserName = $object->FromUserName;
                $fromUserName = json_encode($fromUserName);
                $fromUserName = json_decode($fromUserName,true);
                $fromUserName = $fromUserName[0];
                $latitude = strtolower($object->Latitude);//地理位置纬度
                $longitude = strtolower($object->Longitude);//地理位置经度
                //根据openId 查询游客id
                $data =  M('b2c_temp_user')->where(array('openid'=>$fromUserName))->find();
                //根据游客id加入缓存
                S('Latitude'.$data['t_u_id'],null);
                S('Latitude'.$data['t_u_id'],$latitude);
                S('Longitude'.$data['t_u_id'],null);
                S('Longitude'.$data['t_u_id'],$longitude);
                exit('success');
                //responseText($object, '不约不约,就算你给了我地址'.$data['t_u_id'], true);
                break;
            case "CLICK":
                switch ($object->EventKey)
                {
                    case "FIRST_PAGE":
                        $contentStr[] = array("Title" =>"首页",
                            "Description" =>"一成优选",
                            "PicUrl" =>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg",
                            "Url" =>"weixin://addfriend/pondbaystudio");
                        break;
                    default:
                        $contentStr[] = array("Title" =>"默认菜单回复",
                            "Description" =>"您正在使用的是方倍工作室的自定义菜单测试接口",
                            "PicUrl" =>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg",
                            "Url" =>"weixin://addfriend/pondbaystudio");
                        break;
                }
                break;
            default:
                break;

        }
        if (is_array($contentStr)){
            $resultStr = $this->transmitNews($object, $contentStr);
        }else{
            $resultStr = $this->transmitText($object, $contentStr);
        }
        return $resultStr;
    }
    public function addUser($postarr,$str_id=0){
        if(!isset($postarr->EventKey)){
            return 10;
        }

        $parameter = strtolower($postarr->EventKey);
        $ticket = $postarr->Ticket;
        $fromUserName = $postarr->FromUserName;
        $fromUserName = json_encode($fromUserName);
        $fromUserName = json_decode($fromUserName,true);
        $fromUserName = $fromUserName[0];
        //获取access_token
        //$access_token = accessToken();
        //return $fromUserName;
        //获取用户信息（微信）

        $wx_data = $this->wx_obj->weiXinUserName($fromUserName);
        //return json_encode($wx_data);
        if(!$wx_data){
            return 12;
        }
        //dump($fromUserName);die;
        $obj = M('b2c_temp_user');
        //return $wx_data['openid'];
        //判断是否已经是游客
        $stat = $obj->where(array('openid'=>$wx_data['openid']))->find();
        //return json_encode($stat);
        //查询二维码的门店id
        $code_data = M('b2c_2d_barcode')->where("`barcode_img` ='".$ticket."'")->find();
        //return M()->_sql();
        // todo 保存用户头像（验证时把微信昵称存入正式表中的昵称）

        //str_id 如果  str_id ！= 0 就是分销二维码带进来的

        $arr = array(
            'source_id' => 2,
            'nickname' => $wx_data['nickname'], //后面请求微信接口获取用户信息
            'parameter' => $code_data['b_parameter'],
            'last_parameter' => $code_data['b_parameter'],
            'source_local_id' => $code_data['local_id'],
            'default_local_id' => $code_data['local_id'],
            'weixin_num' => $wx_data['nickname'],
            'openid' => $wx_data['openid'],
            'logo' => $wx_data['headimgurl'],
            'regtime' => time(),
        );
        //$arr['openid']='234';

        //return json_encode($code_data);
        if($stat){

            $data = $obj->where(array('t_u_id'=>$stat['t_u_id']))->find();
            //如果是扫描分销会员二维码进来
            if($str_id != 0){
                $dm_data = M('distribution_member')->where(['id'=>$str_id])->find();
                if(empty($stat['source_local_id'])){
                    $arr['source_local_id'] = $dm_data['local_id'];
                    $arr['default_local_id'] = $dm_data['local_id'];
                }else{
                    $arr['source_local_id'] = $data['source_local_id'];
                    $arr['default_local_id'] = $dm_data['local_id'];
                }

                $stat = $obj->where(array('t_u_id'=>$stat['t_u_id']))->save($arr);
            }else{
                //不是分销扫描进来的

                if($data['last_parameter'] != $parameter && !empty($data['source_local_id']) ){
                    $arr['parameter'] = $data['parameter'];
                    $arr['source_local_id'] = $data['source_local_id'];
                }

                if(empty($code_data)){
                    $arr['default_local_id'] = $data['default_local_id'];
                }

                //return json_encode($arr);
                $stat = $obj->where(array('t_u_id'=>$stat['t_u_id']))->save($arr);
            }

        }else{
//            $stat = $obj->add($arr);

            $members_data = [
                'openid' => $wx_data['openid'],
                'nickname' => $wx_data['nickname']
            ];
            try {
                M()->execute('begin');

                if($str_id != 0){
                    $dm_data = M('distribution_member')->where(['id'=>$str_id])->find();
                    $arr['source_local_id'] = $dm_data['local_id'];
                    $arr['default_local_id'] = $dm_data['local_id'];
                }

                $stat = $obj->add($arr);
                $members_id = M("b2c_members")->add($members_data);
                if ($stat === false || $members_id === false) {
                    throw new \Exception(false);
                }
                M()->execute('commit');
            }catch (\Exception $e){
                M()->execute('rollback');
                $stat === false;
            }
        }
        return $stat === false ? false: $members_id;
    }



    public function addUser_new($postarr,$str_id=0,$addUser_new=0){
        if(!isset($postarr->EventKey)){
            return 10;
        }

        $parameter = strtolower($postarr->EventKey);
        $ticket = $postarr->Ticket;
        $fromUserName = $postarr->FromUserName;
        $fromUserName = json_encode($fromUserName);
        $fromUserName = json_decode($fromUserName,true);
        $fromUserName = $fromUserName[0];
        //获取access_token
        //$access_token = accessToken();
        //return $fromUserName;
        //获取用户信息（微信）

        $wx_data = $this->wx_obj->weiXinUserName($fromUserName);
        //return json_encode($wx_data);
        if(!$wx_data){
            return 12;
        }
        //dump($fromUserName);die;
        $obj = M('b2c_temp_user');
        //return $wx_data['openid'];
        //判断是否已经是游客
        $stat = $obj->where(array('openid'=>$wx_data['openid']))->find();
        //return json_encode($stat);
        //查询二维码的门店id
        $code_data = M('b2c_2d_barcode')->where("`barcode_img` ='".$ticket."'")->find();
        //return M()->_sql();
        // todo 保存用户头像（验证时把微信昵称存入正式表中的昵称）

        //str_id 如果  str_id ！= 0 就是分销二维码带进来的

        $arr = array(
            'source_id' => 2,
            'nickname' => $wx_data['nickname'], //后面请求微信接口获取用户信息
            'parameter' => $code_data['b_parameter'],
            'last_parameter' => $code_data['b_parameter'],
            'source_local_id' => $code_data['local_id'],
            'default_local_id' => $code_data['local_id'],
            'weixin_num' => $wx_data['nickname'],
            'openid' => $wx_data['openid'],
            'logo' => $wx_data['headimgurl'],
            'regtime' => time(),
        );
        //$arr['openid']='234';
        //return json_encode($code_data);
        if($stat){

            //如果是扫描分销会员二维码进来
            if($str_id != 0){

                $dm_data = M('distribution_member')->where(['id'=>$str_id])->find();

                if(empty($stat['source_local_id'])){
                    $arr['source_local_id'] = $dm_data['local_id'];
                    $arr['default_local_id'] = $dm_data['local_id'];
                }else{
                    $arr['default_local_id'] = $dm_data['local_id'];
                }

                //分销情况下
                if($addUser_new == 1){
                    $arr['is_url_add'] = 1;
                    $stat = $obj->where(array('t_u_id'=>$stat['t_u_id']))->save($arr);
                    M('b2c_members')->where(array('openid'=>$wx_data['openid']))->save(['nickname'=>$wx_data['nickname']]);
                    //返回member_id
                    $members_id = M('b2c_members')->where(array('openid'=>$wx_data['openid']))->find()['member_id'];
                }else{
                    $arr['is_url_add'] = $stat['is_url_add'];
                    $stat = $obj->where(array('t_u_id'=>$stat['t_u_id']))->save($arr);
                }

            }/*else{
                //不是分销扫描进来的
                $data = $obj->where(array('t_u_id'=>$stat['t_u_id']))->find();

                if($data['last_parameter'] != $parameter && !empty($data['source_local_id']) ){
                    $arr['parameter'] = $data['parameter'];
                    $arr['source_local_id'] = $data['source_local_id'];
                }

                //return json_encode($arr);
                $stat = $obj->where(array('t_u_id'=>$stat['t_u_id']))->save($arr);
            }*/

        }else{
//            $stat = $obj->add($arr);

            $members_data = [
                'openid' => $wx_data['openid'],
                'nickname' => $wx_data['nickname']
            ];
            try {

                if($str_id != 0){
                    $dm_data = M('distribution_member')->where(['id'=>$str_id])->find();
                    $arr['source_local_id'] = $dm_data['local_id'];
                    $arr['default_local_id'] = $dm_data['local_id'];
                }

                $stat = $obj->add($arr);
                $members_id = M("b2c_members")->add($members_data);
                if ($stat === false || $members_id === false) {
                    throw new \Exception(false);
                }

            }catch (\Exception $e){
                $stat === false;
            }
        }
        return $stat === false ? false: $members_id;
    }


    //分销扫描 进来
    public function is_fx_scan($str_id,$object){

        $fromUserName = $object->FromUserName;
        $fromUserName = json_encode($fromUserName);
        $fromUserName = json_decode($fromUserName,true);
        $fromUserName = $fromUserName[0];



        $fx_one =  M('distribution_member')->where(['id'=>$str_id])->find();


        //1.先判断该用户 是否是第一次关注，（第一次关注根据他的openID 来查询是否有该游客表的记录）
        if(!isset($object->EventKey) || $fx_one === false){
            //微信相应事件不存在，或者分销二维码扫描查询上级数据异常
            M('test')->add(['msg'=>'微信相应事件不存在，或者分销二维码扫描查询上级数据异常：'.$fromUserName]);
            return array('status' => false, 'msg' => 'err01');
        }



        //获取access_token
        //获取用户信息（微信）
        $wx_data = $this->wx_obj->weiXinUserName($fromUserName);

        //判断是否已经是游客

        if(empty($wx_data['openid'])){
            M('test')->add(['msg'=>'openid是空：'.$fromUserName]);
            return array('status' => false, 'msg' => '网络异常，请取消关注，重新关注！');
        }


        $stat = M('b2c_temp_user')->where(array('openid'=>$wx_data['openid']))->find();
        $url_add = M('b2c_temp_user')->where(array('openid'=>$wx_data['openid'],'is_url_add'=>2))->find();


        if(empty($stat) || !empty($url_add)){

            if($stat === false){
                $stat = M('b2c_temp_user')->where(array('openid'=>$wx_data['openid']))->find();
            }

            if(!empty($url_add)){
                //是url带来新用户
                 $is_url_new_user = 1;
            }else{
                //不是url带来新用户
                $is_url_new_user = 0;
            }

            if($stat !== false && $url_add !==false){
                //正常新用户
                //已经是新用户，加入游客信息
                M('test')->add(array('openid'=>$wx_data['openid'],'msg'=>'已经是新用户，加入游客信息'));
                $Mod = M();

                try{
                    $Mod->startTrans();
                    $stat = $this->addUser_new($object,$str_id,$is_url_new_user);

                    if ($stat === false) { throw new \Exception('添加用户失败！'); }

                    //该店铺 是否启动，并且启动分销
                    $sj_user_iscan = M('webpos_local_store ls')
                        ->join('left join sdb_distribution_member dm on ls.local_id = dm.local_id')
                        ->where(['dm.id'=>$fx_one['id'],'ls.is_open_distribution'=>'1','ls.local_status'=>'1'])->find();

                    if (!empty($sj_user_iscan)) {
                        //[满足开启条件]
                        //3.上下级绑定 入库sdb_distribution_member 表记录 (绑定用户跟上级的关系)
                        //设置的奖金
                        $gift_money_friend =   M('store_distribution_set')->where(['local_id'=>$fx_one['local_id'],'set_name'=>'follow_wechat_friend'])->find()['set_value'];

                        if(empty($gift_money_friend)){
                            $gift_money_friend = 0;
                        }else{
                            //推送消息给下级用户
                            $child = M('b2c_members')->where(['member_id'=>$stat])->find();
                            if ($child === false) { throw new \Exception('查询下级用户出错！'); }



                            $res_weixin_c = WeixinSonMemberGetMoney($fx_one['local_id'],$child['openid'],$child['nickname'],$gift_money_friend);
                            if($res_weixin_c['errcode'] != 0){throw new \Exception('推送消息失败！');}

                            //新用户通过朋友扫描获取奖金
                            $log_add_n_money = M('b2c_bonus_log')->add([
                                'local_id'=>$fx_one['local_id'],
                                'member_id'=>$stat,
                                'type'=>'0',
                                'change'=>'9',
                                'change_num'=>$gift_money_friend,
                                'time'=>time(),
                                'msg'=>'新用户通过朋友扫描获取奖金',
                                's_member_id'=>0,

                            ]);
                            if ($log_add_n_money === false) { throw new \Exception('添加更改记录失败！'); }
                        }

                        $res =   M('distribution_member')->add([
                            'local_id' => $fx_one['local_id'],
                            'member_id' => $stat,
                            'p_member_id' => $fx_one['member_id'],
                            'friend_num' => 0,
                            'count_bonus' => $gift_money_friend,
                            'current_bonus' => $gift_money_friend,
                            'create_time' => date('Y-m-d H:i:s', time()),
                        ]);


                        if ($res === false) { throw new \Exception('添加新用户关系记录失败！'); }

                        //更新上级用户的 奖金数据
                        $sj_user = M('distribution_member')->where(['member_id'=>$fx_one['member_id'],'local_id'=>$fx_one['local_id']])->find();

                        if ($sj_user === false || empty($sj_user)) { throw new \Exception('查询分销用户失败！'); }

                        //设置的奖金
                        $gift_money =   M('store_distribution_set')->where(['local_id'=>$fx_one['local_id'],'set_name'=>'follow_wechat'])->find()['set_value'];

                        if(!empty($gift_money)){

                            //当设置奖金不为空
                            $friend_num_new = $sj_user['friend_num'] + 1;
                            $count_bonus_new = $sj_user['count_bonus'] + $gift_money;
                            $current_bonus = $sj_user['current_bonus'] + $gift_money;
                            $sa = M('distribution_member')->where(['id'=>$sj_user['id']])->save([
                                'friend_num' => $friend_num_new,
                                'count_bonus' => $count_bonus_new,
                                'current_bonus' => $current_bonus,
                            ]);
                            if ($sa === false) { throw new \Exception('更新上级用户金额失败！'); }
                            //4.推送消息

                            $father = M('b2c_members')->where(['member_id'=>$fx_one['member_id']])->find();
                            $child = M('b2c_members')->where(['member_id'=>$stat])->find();
                            if ($father === false || empty($father)) { throw new \Exception('查询上级用户出错！'); }
                            $res_weixin = WeixinAttentionToFatherMember($fx_one['local_id'],$father['openid'],$child['nickname'],$gift_money);

                            if($res_weixin['errcode'] != 0){throw new \Exception('推送消息失败！');}

                            //5.日志表
                            $log_add = M('b2c_bonus_log')->add([
                                'local_id'=>$fx_one['local_id'],
                                'member_id'=>$fx_one['member_id'],
                                'type'=>'0',
                                'change'=>'1',
                                'change_num'=>$gift_money,
                                //'param'=>$log_add,
                                'time'=>time(),
                                'msg'=>'下级用户关注公众号',
                                's_member_id'=>$stat,

                            ]);
                            if ($log_add === false) { throw new \Exception('添加更改记录失败！'); }
                        }

                    }

                    $Mod->commit();

                }catch (\Exception $e){
                    // 事务回滚
                    $Mod->rollback();
                    M('test')->add(['msg'=>$e->getMessage().$fromUserName,'openid'=>$wx_data['openid']]);
                    return array('status' => false, 'msg' => '网络异常，请取消关注，重新关注！');
                }

            }else{
                //判断是否已经是游客 sql报错
                M('test')->add(['msg'=>'判断空用户sql出错：'.$fromUserName,'openid'=>$wx_data['openid']]);
                return array('status' => false, 'msg' => '网络异常，请取消关注，重新关注！');
            }
        }else{
            $stat_res = $this->addUser($object,$str_id);
            M('test')->add(['msg'=>'判断是否已经是游客出错：'.$fromUserName,'openid'=>$wx_data['openid']]);
            return array('status' => $stat_res, 'msg' => '网络异常，请取消关注，重新关注！');
        }


    }




}